<template>
  <div class="layout-container column-layout">
    <div class="provided-header app-container flex space-between align-center">
      <div class="left-header flex align-center">
        <div class="icon"></div>
        <div class="left-header-name">生成合同文件</div>
      </div>
    </div>
    <div class="app-container provided-content">
      <el-input v-model="templateData.templateName" placeholder="请输入合同标题" disabled />
      <div>
        <div v-for="item in templateData.templateContentList" :key="item.contractTemplateId">
          <div class="main-content-title">{{ item.templateContentTitle }}</div>
          <div
            v-html="item.templateContent"
            v-if="
              item.templateContentKey.toString().includes('shop_materials_list_project_budget') ||
              item.templateContentKey.toString().includes('shop_list_ys_budget')
            "
          ></div>
          <EditorInput v-else v-model="item.templateContent" :is-disabled="!item.isModifiable" editId="mainContent" />
        </div>
      </div>
    </div>
    <div class="filed-content">
      <el-collapse-transition>
        <div v-show="show">
          <div class="upload-file-li">
            <div v-for="(item, index) in fileListData" :key="item" class="upload-file-item">
              <el-image style="width: 24px; height: 24px" :src="item.fileUrl" :preview-src-list="[item.fileUrl]">
                <template #error>
                  <div class="image-slot">
                    <img style="width: 24px; height: 24px" src="@/assets/images/errpdf.png" alt="" />
                  </div>
                </template>
              </el-image>
              <div class="flile-name">{{ item.name || item.fileName }}</div>
              <img class="del-img" src="@/assets/images/del.png" alt="" @click="handleRemove(index)" />
            </div>
          </div>
        </div>
      </el-collapse-transition>
    </div>
    <div class="provided-footer">
      <div style="display: flex">
        <div v-if="templateData.signingMethod === 2" class="provided-upload" @click="handleUplod">
          <img src="@/assets/images/errpdf.png" alt="" />上传附件
        </div>
        <div class="open-file" @click="show = !show" v-if="templateData.signingMethod === 2 && fileListData.length > 0">
          {{ show ? "收起" : "展开" }}
          <img src="@/assets/images/sq.png" alt="" v-if="show" />
          <img src="@/assets/images/zk.png" alt="" v-else />
        </div>
      </div>
      <div>
        <el-button type="info" class="close-but" @click="handleCancel">取消</el-button>
        <el-button type="primary" class="" @click="handleGenerateContracts" :loading="loadingCreate">生成合同 </el-button>
      </div>
    </div>
    <!-- 上传签约合同 -->
    <el-dialog
      v-model="pdfDialogVisible"
      title="上传附件"
      width="485px"
      style="margin-top: 150px !important; border-radius: 10px"
      center
      :before-close="handleClose"
    >
      <div v-loading="loading" element-loading-text="上传中">
        <pdf-upload
          v-if="pdfDialogVisible"
          :fileList="contractAttachment"
          :accept="'.pdf,.doc,.docx,.xls,.xlsx'"
          multiple
          :max-size="20"
          :max-length="50"
          uploadName="上传附件"
          tips="支持上传PDF/word/excel等常见规格，单个附件不超过20M，最多上传50个"
          @upload-success="uploadSuccess"
          @upload-remove="uploadRemove"
        />
      </div>
      <template #footer>
        <div class="upload-but" style="text-align: center">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="postUpload" :disabled="contractAttachment.length <= 0">确认上传</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 作废弹窗   -->
    <div class="create-dialog">
      <el-dialog :show-close="false" v-model="dialogVisible" width="578px" center>
        <div>
          <img class="create-img" src="@/assets/images/success.png" alt="" />
          <div>合同文件生成成功，你现在要下载此合同文件吗？</div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleCloseFild">取消</el-button>
            <el-button type="primary" @click="handleDown">下载</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog :show-close="false" v-model="visible" width="578px" center title="选择附件">
        <div style="text-align: left">
          <div style="font-weight: 500; color: #131414">选择需拼接至合同主体内容的附件</div>
          <div>拼接的文件格式支持pdf、word、excel，word和excel不可有图片和视频</div>
        </div>
        <el-checkbox-group v-model="spliceContracts" style="display: flex; flex-wrap: wrap; margin: 0 10px">
          <el-checkbox v-for="item in fileListData" :key="item" :label="item.fileName" :value="item">
            <el-tooltip class="box-item" effect="dark" :content="item.fileName" placement="top-start">
              <div class="check-name">{{ item.fileName }}</div>
            </el-tooltip>
            <div class="check-name"></div>
          </el-checkbox>
        </el-checkbox-group>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleCloseChecked">取消</el-button>
            <el-button type="primary" @click="handlePreview" :loading="loadingPreview">预览</el-button>
            <el-button type="primary" @click="handleGenerate(2)" :loading="loadingCreate">生成合同</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <!-- 查看合同   -->
    <file-preview ref="roleRef" @handleGenerate="handleGenerate" :loadingCreate="loadingCreate" />
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useRoute } from "vue-router";
import router from "@/router/index.js";
import { ElMessage } from "element-plus";
import { cloneDeep } from "lodash";
import { microAppMainRouter } from "@/microApp/utils.js";
import { contractPdf, contractTemplateConfig, getContract, templateDetail } from "@/apis/template/index.js";
import { setBottomhtml, setbudget, setHtml, setTophtml, siveHtml, setTableHtml } from "@/views/contractsProvided/setHtml.js";
import { downloadPDF } from "@/utils/util.js";
import { selectDictDataByType } from "@/apis/dict/dict.js";

const route = useRoute();
const baseFields = ref([]); //
const contractAttachment = ref([]); //
const fileListData = ref([]); //
const spliceContracts = ref([]); //
const loading = ref(false);
const dialogVisible = ref(false);
const pdfDialogVisible = ref(false);
const loadingCreate = ref(false);
const loadingPreview = ref(false);
const show = ref(false);
const objData = ref({});
const pdfUrl = ref("");
const htmlAll = ref("");
const templateData = ref({});
const contractCode = ref({}); // 编号
const initContentList = ref([]);
const softDecorationStatus = ref(0);
const unitData = ref([]);
const moneyType = ref([]);
const visible = ref(false);
const roleRef = ref();
const fileName = ref("");

// 详情
const getTemplateDetail = async () => {
  const { data } = await templateDetail(route.query.contractId);
  if (data.templateContentList?.length) {
    contractCode.value = cloneDeep(data.templateContentList[0]);
    const templateContentList =
      data.templateContentList?.map((item, index) => {
        if (index > 1) {
          let templateConfig = [];
          item.isRead && templateConfig.push(1);
          item.isSign && templateConfig.push(2);
          item.templateConfig = [...templateConfig];
          if (item.templateContent && isJSON(item.templateContent)) {
            const { topImg, bottomImg, templateContent } = JSON.parse(item.templateContent);
            item.bottomImgList = [...bottomImg];
            item.topImgList = [...topImg];
            item.templateContent = templateContent;
          }
          return item;
        } else {
          return item;
        }
      }) || [];
    data.templateContentList = [...templateContentList.slice(1)];
  }
  templateData.value = data;
  await getContractData(data);
  let dataAll = cloneDeep(data);
  initContentList.value = cloneDeep(data);
  initContentList.value.templateContentList = [{ ...contractCode.value }, ...dataAll.templateContentList];
};
const isJSON = str => {
  return typeof str === "string" && str.length > 0 && str[0] === "{" && str[str.length - 1] === "}";
};
// 获取模板字符串配置
const getContractTemplateConfig = async () => {
  const { data } = await contractTemplateConfig();
  const arrData = [];
  (data.length > 0 &&
    data.map(item => {
      item.content.map(items => {
        arrData.push(items);
      });
    })) ||
    [];
  baseFields.value = arrData;
  setName();
};

const setName = () => {
  const obj = {};
  let templateContents = "";
  let topImgLists = [];
  let bottomImgLists = [];
  let html = "";
  let bottomHtml = "";
  Object.keys(objData.value).forEach(key => {
    baseFields.value.map(item => {
      if (item.contentKey === key) {
        obj[item["name"]] = cloneDeep(objData.value[key]);
      }
    });
  });
  templateData.value.templateContentList.map(item => {
    templateContents = cloneDeep(item.templateContent);
    topImgLists = (item.topImgList && item.topImgList.length > 0 && cloneDeep(item.topImgList)) || [];
    bottomImgLists = (item.bottomImgList && item.bottomImgList.length > 0 && cloneDeep(item.bottomImgList)) || [];
    // 收款计划
    if (topImgLists.length > 0) {
      html = setTophtml(objData.value.other_receive_plain);
      templateContents = html += templateContents;
    }
    if (bottomImgLists.length > 0) {
      bottomHtml = setBottomhtml(objData.value.other_receive_plain);
      templateContents = templateContents += bottomHtml;
    }
    Object.keys(obj).forEach(key => {
      const regex = new RegExp(`\\\${${key}}`, "g");
      templateContents = templateContents.replace(regex, match => {
        if (match === "${工程预算清单}" || match === "${预算报价单}") {
          if (softDecorationStatus.value !== 1) {
            let htmlOne = "";
            htmlOne = setHtml(objData.value.shop_materials_list_project_budget, item.isHorizontal);
            htmlOne += siveHtml(objData.value.shop_materials_list_project_budget, moneyType.value);
            htmlOne += setbudget(objData.value.shop_materials_list_project_budget);
            return htmlOne;
          } else {
            return setTableHtml(objData.value.shop_materials_list_project_budget, unitData.value);
          }
        } else if (match === "${甲方签字区}") {
          return "甲方（签字）：";
        } else if (match === "${乙方签章区}") {
          return "乙方（公章）：";
        } else {
          return obj[key] || "";
        }
      });
    });
    item.templateContent = cloneDeep(templateContents);
  });
};
// 点击上传附件
const handleUplod = () => {
  pdfDialogVisible.value = true;
  contractAttachment.value = [];
};
// 获取成功上传的附件
const uploadSuccess = data => {
  contractAttachment.value.push({ ...data });
};
// 删除上传
const uploadRemove = index => {
  contractAttachment.value.splice(index, 1);
};
// 删除上传
const handleRemove = index => {
  fileListData.value.splice(index, 1);
};
// 关闭上传
const handleClose = () => {
  contractAttachment.value = [];
  pdfDialogVisible.value = false;
};
const postUpload = async () => {
  fileListData.value = fileListData.value.concat(cloneDeep(contractAttachment.value));
  ElMessage.success("附件添加成功");
  pdfDialogVisible.value = false;
  contractAttachment.value = [];
};
// 生成合同判断是否有附件
const handleGenerateContracts = () => {
  if (fileListData.value.length > 50) {
    ElMessage.error("附件不能超过50个");
    return;
  }
  if (fileListData.value.length !== 0) {
    visible.value = true;
    spliceContracts.value = [];
  } else {
    handleGenerate(2);
  }
};
// 预览
const handlePreview = () => {
  handleGenerate(1);
};
// 确认生成合同 step  1 预览，2 生成， 3 预览后生成合同
const handleGenerate = async step => {
  if (step === 1) loadingPreview.value = true;
  if (step !== 1) loadingCreate.value = true;
  htmlAll.value = "";
  templateData.value.templateContentList.forEach(item => {
    htmlAll.value += item.templateContent;
  });
  let dataAll = cloneDeep(templateData.value);
  dataAll.contractAttachment = fileListData.value;
  dataAll.contractAttachment2 = spliceContracts.value; //拼接附件
  dataAll.templateContentList = [{ ...contractCode.value }, ...dataAll.templateContentList];
  dataAll.templateContentList.forEach((item, i) => {
    if (item.templateContent !== initContentList.value.templateContentList[i].templateContent) {
      item.change = true;
    }
  });
  try {
    const { msg } = await contractPdf({
      ...dataAll,
      contractId: route.query.contractId,
      contractStr: htmlAll.value,
      title: route.query.title,
      step,
      fileName: fileName.value
    });
    fileName.value = msg;
    if (step === 1) {
      roleRef.value.generateShow = true;
      loadingPreview.value = false;
      roleRef.value.openPdf(msg);
      visible.value = false;
    } else {
      visible.value = false;
      roleRef.value.close();
      dialogVisible.value = true;
      pdfUrl.value = msg;
      loadingCreate.value = false;
    }
  } catch (e) {
    loadingCreate.value = false;
  }
};
// 查看合同模板数据
const getContractData = async () => {
  const { data } = await getContract(route.query.contractId);
  data.sign_area_sign_company = "";
  data.sign_area_sign_customer = "";
  objData.value = data;
  softDecorationStatus.value = data.shop_materials_list_project_budget.softDecorationStatus;
  fileListData.value = data.contractAttachmentList || [];
  await getContractTemplateConfig();
};

// 取消
const handleCancel = () => {
  if (route.query.customerId) {
    microAppMainRouter("push", {
      path: "/crm/client-info",
      query: {
        customerId: route.query.customerId
        // funcTab: "contractMaterials"
      }
    });
  } else {
    router.push({ path: "/" });
  }
};
const handleDown = async () => {
  const name = pdfUrl.value.slice(pdfUrl.value.lastIndexOf("/") + 1);
  const parts = name.split("-");
  const newParts = parts.slice(0, 2);
  const newFileName = newParts.join("-") + ".pdf";
  await downloadPDF(pdfUrl.value, newFileName);
  handleCancel();
};
const handleCloseFild = () => {
  dialogVisible.value = false;
  handleCancel();
};
// 取消选择拼接附件
const handleCloseChecked = () => {
  visible.value = false;
  spliceContracts.value = [];
};
const getUnit = async () => {
  const { data } = await selectDictDataByType("shop_unit");
  unitData.value = data || [];
};
const getMoneyType = async () => {
  const { data } = await selectDictDataByType("shop_budget_money_type");
  moneyType.value = data || [];
};
getUnit();
getMoneyType();
getTemplateDetail();
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
